<template>
    <div class="body identy">
        <div class="box">
            <h2>*个人信息</h2>

            <h3>
                <label class="labeltit">姓名</label>
                <input type="text" placeholder="请输入姓名" v-model="name" />
            </h3>
            <h3>
                <label class="labeltit">手机号</label>
                <input type="tel" placeholder="请输入手机号" v-model="phoneL" />
            </h3>
            <h4 class="labeltit">身份证</h4>

            <ul>
                <li>
                    <div
                        @click="checkimg(0)"
                        :class="{ divactive: checkImg0 != '' }"
                    >
                        <img v-if="checkImg0 != ''" :src="checkImg0" alt="" />
                    </div>
                    <input
                        ref="filElem0"
                        required="required"
                        type="file"
                        accept="image/*"
                        name="report"
                        @change="getFile($event, 0)"
                    />
                    <p>身份证正面</p>
                </li>
                <li>
                    <div
                        @click="checkimg(1)"
                        :class="{ divactive: checkImg0 != '' }"
                    >
                        <img v-if="checkImg1 != ''" :src="checkImg1" alt="" />
                    </div>
                    <input
                        ref="filElem1"
                        required="required"
                        type="file"
                        accept="image/*"
                        name="report"
                        @change="getFile($event, 1)"
                    />
                    <p>身份证反面</p>
                </li>
            </ul>

            <h5 @click="queding()"><span>立即申请</span></h5>

            <h6>
                <!-- <img src="../img/wjwlogo.png" alt="" /> -->
            </h6>
        </div>
    </div>
</template>

<script>
import { Toast } from "mint-ui";
export default {
    name: "identity",
    data() {
        return {
            checkImg0: "",
            checkImg1: "",
            datacheckImg0: "",
            datacheckImg1: "",
            phoneL: "",
            name: "",
            keystate: true
        };
    },
    methods: {
        queding() {
            if (!this.keystate) {
                return;
            }
            if (!/^1[3456789]\d{9}$/.test(this.phoneL.replace(/\s+/g, ""))) {
                return Toast({
                    message: "请输入正确的手机号码",
                    duration: 1000
                });
            }
            if (this.name == "") {
                return Toast({
                    message: "请输入姓名",
                    duration: 1000
                });
            }
            if (this.datacheckImg0 == "" || this.datacheckImg1 == "") {
                return Toast({
                    message: "请上传图片",
                    duration: 1000
                });
            }
            this.keystate = false;
            const data = {
                name: this.name,
                mobile: this.phoneL.replace(/\s+/g, ""),
                idCard0: this.datacheckImg0,
                idCard1: this.datacheckImg1
            };
            console.log(data);
            this.axios({
                method: "post",
                url: this.common.baseURL + "/cpa",
                headers: {
                    "Content-Type": "application/json"
                },
                data: JSON.stringify(data),
                withCredentials: true
            }).then(response => {
                setTimeout(() => {
                    this.keystate = true;
                }, 100);
                console.log(response.data);
                if (response.data.code == -8) {
                    return this.$router.push({
                        path: "/login",
                        query: { selected: "2" }
                    });
                }
                if (response.data.code != 0) {
                    return Toast({
                        message: "图片上传错误，请重新上传！",
                        duration: 1000
                    });
                }
                this.$router.push({
                    path: "/success",
                    query: { selected: "2" }
                });
            });
        },
        checkimg(id) {
            if (id === 0) {
                this.$refs.filElem0.dispatchEvent(new MouseEvent("click"));
            } else {
                this.$refs.filElem1.dispatchEvent(new MouseEvent("click"));
            }
        },
        getFile(e, id) {
            let that = this;
            const inputFile = e.target.files[0];
            if (inputFile) {
                if (
                    inputFile.type !== "image/jpeg" &&
                    inputFile.type !== "image/png" &&
                    inputFile.type !== "image/gif"
                ) {
                    return Toast({
                        message: "不是有效的图片文件！",
                        duration: 1000
                    });
                }
                const reader = new FileReader();
                reader.readAsDataURL(inputFile);
                reader.onload = function() {
                    that.imgstate = 4;
                    that.imgSrc = this.result;
                    let img = new Image();
                    img.src = this.result;
                    var width = 400, //图像大小
                        height = 400, //图像大小
                        quality = 1, //图像质量
                        canvas = document.createElement("canvas"),
                        drawer = canvas.getContext("2d");
                    img.onload = function() {
                        const originHeight = img.height;
                        const originWidth = img.width;
                        let compressedWidth = img.height;
                        let compressedHeight = img.width;
                        if (originWidth > width && originHeight > height) {
                            // 更宽更高，
                            if (originHeight / originWidth > height / width) {
                                // 更加严重的高窄型，确定最大高，压缩宽度
                                compressedHeight = height;
                                compressedWidth =
                                    height * (originWidth / originHeight);
                            } else {
                                //更加严重的矮宽型, 确定最大宽，压缩高度
                                compressedWidth = width;
                                compressedHeight =
                                    width * (originHeight / originWidth);
                            }
                        } else if (
                            originWidth > width &&
                            originHeight <= height
                        ) {
                            // 更宽，但比较矮，以width作为基准
                            compressedWidth = width;
                            compressedHeight =
                                width * (originHeight / originWidth);
                        } else if (
                            originWidth <= width &&
                            originHeight > height
                        ) {
                            // 比较窄，但很高，取maxHight为基准
                            compressedHeight = height;
                            compressedWidth =
                                height * (originWidth / originHeight);
                        } else {
                            // 符合宽高限制，不做压缩
                        }
                        canvas.width = compressedWidth;
                        canvas.height = compressedHeight;
                        drawer.drawImage(
                            img,
                            0,
                            0,
                            canvas.width,
                            canvas.height
                        );
                        //console.log(canvas.toDataURL("image/jpg", quality));

                        const base64String = canvas.toDataURL(
                            "image/jpg",
                            quality
                        );
                        const bytes = window.atob(base64String.split(",")[1]);

                        //处理异常，将ASCII码小于0的转换为大于0，这里有两种写法
                        const ab = new ArrayBuffer(bytes.length);
                        const ia = new Uint8Array(ab);
                        for (var i = 0; i < bytes.length; i++) {
                            ia[i] = bytes.charCodeAt(i); //这里有点疑惑，ia是怎么改变ab的？注：①
                        }
                        //Blob对象
                        const blob = new Blob([ab], { type: "image/jpeg" }); //type为图片的格式

                        //FormData对象
                        let formedate = new FormData();
                        //TDOD Ajax或者其他方式上传FormData对象

                        //FormData对象接受三个参数，第三个参数为文件名，通常我们只传前两个参数，第三个参数不传则使用默认文件名，这里使用的Blob对象，所以需要一个文件名，用时间戳代替。
                        formedate.append("file", blob, Date.now() + ".jpg");

                        that.axios({
                            method: "post",
                            url: that.common.baseURL + "/upload",
                            headers: {
                                "Content-Type": "multipart/form-data"
                            },
                            data: formedate,
                            withCredentials: true,
                            contentType: false,
                            processData: false
                        }).then(response => {
                            if (response.data.code == -8) {
                                return that.$router.push({
                                    path: "/login",
                                    query: { selected: "2" }
                                });
                            }
                            if (response.data.code != 0) {
                                return Toast({
                                    message: "图片上传错误，请重新上传！",
                                    duration: 1000
                                });
                            }
                            if (id == 0) {
                                that.datacheckImg0 = response.data.data;
                                that.$refs.filElem0.value = "";
                                that.checkImg0 = canvas.toDataURL(
                                    "image/jpg",
                                    quality
                                );
                            } else {
                                that.datacheckImg1 = response.data.data;
                                that.$refs.filElem1.value = "";
                                that.checkImg1 = canvas.toDataURL(
                                    "image/jpg",
                                    quality
                                );
                            }
                        });
                    };
                };
            } else {
                return;
            }
        }
    }
};
</script>

<style scoped lang="less">
.identy {
    .box {
        padding: 0.5rem;
        h2 {
            font-size: 0.36rem;
            font-weight: 600;
            line-height: 50px;
            color: #323232;
        }
        .labeltit {
            font-size: 0.28rem;
            font-weight: 600;
            line-height: 40px;
            color: #323232;
            width: 1.4rem;
            display: inline-block;
        }
        h3 {
            ::placeholder {
                font-size: 0.24rem;
                font-weight: 400;
                color: #c1c1c1;
            }
            input {
                height: 0.6rem;
                padding: 0 0.1rem;
                border: 0;
                font-size: 0.28rem;
            }
        }
        ul {
            li:nth-child(1) div {
                background: #f5f5f5 url(../img/check0.png) center center
                    no-repeat;
                background-size: 80%;
            }
            li:nth-child(2) div {
                background: #f5f5f5 url(../img/check2.png) center center
                    no-repeat;
                background-size: 80%;
            }
            li {
                position: relative;
                overflow: hidden;
                input {
                    position: absolute;
                    top: -100px;
                }
                .divactive {
                    border: 0;
                    width: 6.06rem;
                }
                div {
                    width: 4.06rem;
                    min-height: 2.55rem;
                    background: #f5f5f5;
                    border: 1px solid #707070;
                    opacity: 1;
                    border-radius: 0.15rem;
                    margin: 0 auto;

                    img {
                        width: 100%;
                    }
                }

                p {
                    font-size: 0.28rem;
                    font-weight: 600;
                    color: #323232;
                    text-align: center;
                    line-height: 0.6rem;
                    margin-bottom: 0.2rem;
                }
            }
        }
        h5 {
            height: 0.98rem;
            background: #105ffe;
            border-radius: 0.1rem;
            margin: 0.4rem 0;
            width: 6.5rem;
            font-size: 0.4rem;
            font-weight: 600;
            color: #ffffff;
            text-align: center;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        h6 {
            img {
                width: 2.17rem;
                display: block;
                margin: 0 auto;
            }
        }
    }
}
</style>
